<template>
  <div class="page_content">
    <ElTabs type="card" v-model="tabsBindValuesClarify" class="page_content_tabs">
      <ElTabPane v-for="item in tabsUserName" :name="item" :key="item" :label="item">
        <template #label>
          <span class="custom-tabs-label">
            <span class="page_content_titleValue">{{ item }}</span>
          </span>
        </template>
        <template #default>
          <div class="page_content_unit">
            <div class="left">
              <ElContainer>
                <ElAside>
                  <div class="page_content_unit_tree">
                    <ElementTree :data="TreeList" :isUser="true" />
                  </div>
                </ElAside>
                <ElMain style="padding-top: 0">
                  <div
                    style="
                      display: flex;
                      flex-direction: column;
                      align-items: center;
                      justify-content: space-between;
                      height: 100%;
                    "
                  >
                    <div class="table_content_search">
                      <div class="search">
                        <ElInput
                          v-model="state.name"
                          placeholder="对象名回车后查询"
                          style="height: 38px; width: 300px"
                          @keyup.enter="handleKey"
                        />
                      </div>
                      <div class="button">
                        <ElButton type="primary" :icon="Search" @click="handleKey">查询</ElButton>
                      </div>
                    </div>
                    <div class="page_content_unit_tables">
                      <ElTable
                        ref="TablesData"
                        :data="
                          state.tableData.slice(
                            (state.currentPage - 1) * state.pageSize,
                            state.currentPage * state.pageSize,
                          )
                        "
                        style="width: 100%"
                        :max-height="600"
                        border
                        table-layout="fixed"
                        :row-key="(row) => row.userId"
                        @selection-change="handleSelectionChange"
                      >
                        <ElTableColumn :reserve-selection="true" type="selection" width="55" />
                        <ElTableColumn prop="name" label="对象名" />
                      </ElTable>
                      <div style="margin-top: 20px">
                        <ElPagination
                          @size-change="handleSizeChange"
                          @current-change="handleCurrentChange"
                          :current-page="state.currentPage"
                          :page-sizes="[1, 5, 10, 20]"
                          background
                          :page-size="state.pageSize"
                          layout="prev, pager, next, sizes, jumper"
                          :total="state.total"
                        />
                      </div>
                    </div>
                    <ElButton @click="handleClickText" type="primary">确定</ElButton>
                  </div>
                </ElMain>
                <div class="page_content_group">
                  <ElButton type="warning" @click="handleEmpty">清空</ElButton>
                  <ElButton @click="handleCreate" type="primary">创建组</ElButton>
                  <div class="list" v-for="(items, index) in groupData" :key="index">
                    <span>{{ items.name }}</span>
                    <SvgIcon @click="handleDelete(items.userId)" name="jstree-delete" />
                  </div>
                </div>
              </ElContainer>
            </div>
          </div>
        </template>
      </ElTabPane>
    </ElTabs>
    <ElDialog
      :model-value="createShow"
      title="创建分组"
      :before-close="handleClose"
      :destroy-on-close="true"
    >
      <ElementForm
        ref="myform"
        :loadKey="formData.loadKey"
        :formFields="formData.formFields"
        :formRules="formData.formRules"
        :labelWidth="labelWidth"
        @update:value="hanldFromData"
      >
        <div style="text-align: center">
          <ElButton type="primary" :loading="loadingIcon" @click="getForm">提交</ElButton>
          <ElButton @click="reset">重置表单</ElButton>
        </div>
      </ElementForm>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import qs from 'qs';
  import { tabsUserName, formData } from './index';
  import {
    getTreEnterprise,
    getTreeSupplier,
    getOrgData,
    getGroupSave,
    getTreeGroup,
    getUserGroupData,
  } from '@/api/userChoice';
  import { Search } from '@element-plus/icons-vue';
  import useLoading from '@/hooks/loading';
  import { throttle } from 'lodash-es';
  const { loadingIcon, setLoading } = useLoading();
  const myform = ref<any>(null);
  const TreeList = ref<Array<Namespace.unitTree>>();
  const submitData = ref<Namespace.userGroup>();
  const tabsBindValuesClarify = ref<string>('核心企业');
  const createShow = ref<boolean>(false);
  const labelWidth = ref<number>(110);
  const groupData = ref<Array<Namespace.userDataType>>([]);
  const TablesData = ref<any>();
  const selectUser = ref<any>();
  interface state {
    tableData: Array<Namespace.userDataType>;
    total: number;
    pageSize: number;
    currentPage: number;
    name: string;
    filterTableData: any[];
    MultiSelectData: Array<Namespace.userDataType>;
    queryData: Array<Namespace.userDataType>;
  }
  const state: state = reactive({
    tableData: [],
    total: 0,
    pageSize: 10,
    currentPage: 1,
    name: '',
    filterTableData: [],
    MultiSelectData: [],
    queryData: [],
  });
  onMounted(() => {
    getTreeDataEnterprise();
    window.addEventListener('message', handleMessage);
  });
  const handleMessage = (event) => {
    if (event.data.length) {
      groupData.value = event.data;
    }
  };
  const handleClickText = () => {
    window.parent.postMessage(JSON.stringify(groupData.value));
  };
  watch(tabsBindValuesClarify, (value: string) => {
    if (value == '核心企业') {
      getTreeDataEnterprise();
      state.tableData = [];
      state.total = 0;
      state.currentPage = 1;
      state.pageSize = 10;
    } else if (value == '供应商') {
      getTreeSDataupplier();
      state.tableData = [];
      state.total = 0;
      state.currentPage = 1;
      state.pageSize = 10;
    } else {
      getTreeDaraGroup();
      state.tableData = [];
      state.total = 0;
      state.currentPage = 1;
      state.pageSize = 10;
    }
  });

  const getTreeDataEnterprise = async () => {
    const { data } = await getTreEnterprise();
    TreeList.value = [data];
  };
  const getTreeSDataupplier = async () => {
    const { data } = await getTreeSupplier();
    TreeList.value = [data];
  };
  const getTreeDaraGroup = async () => {
    const { data } = await getTreeGroup();
    if (!data.length) {
      TreeList.value = '' as any;
    } else {
      TreeList.value = data as unknown as Array<Namespace.unitTree>;
    }
  };
  const handleKey = async () => {
    if (state.name) {
      state.name = state.name.toLowerCase();
      state.tableData = state.queryData.filter((item: Namespace.userDataType) => {
        return item.name.includes(state.name);
      });
      state.total = state.tableData.length;
      state.currentPage = 1;
      state.pageSize = 10;
    } else {
      const { data } = await getOrgData({ orgId: selectUser.value.id });
      state.tableData = data;
      state.queryData = data;
      state.total = data.length;
    }
  };
  const handleSelectionChange = async (value) => {
    value.forEach((element) => {
      if (!groupData.value.includes(element)) {
        groupData.value?.push(element);
      }
    });
  };
  const handleEmpty = () => {
    ElMessageBox.confirm('是否清空?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      groupData.value = [];
      ElMessage({
        type: 'success',
        message: '成功！',
      });
    });
  };
  const sendHandleSelectUser = async (value) => {
    if (value) {
      if (tabsBindValuesClarify.value != '我的用户组') {
        selectUser.value = value;
        const { data } = await getOrgData({ orgId: value.id });
        state.tableData = data;
        state.queryData = data;
        state.total = data.length;
      } else {
        selectUser.value = value;
        const { data } = await getUserGroupData({ userGroupId: value.id });
        state.tableData = data;
        state.queryData = data;
        state.total = data.length;
      }
    }
  };
  const handleSizeChange = (value: number) => {
    state.currentPage = 1;
    state.pageSize = value;
  };
  const handleCurrentChange = (value: number) => {
    state.currentPage = value;
  };
  const sendHandleRemove = async (value: boolean) => {
    if (value) {
      getTreeDaraGroup();
      state.tableData = [];
      state.total = 0;
      state.currentPage = 1;
      state.pageSize = 10;
    }
  };
  provide('sendHandleSelectUser', sendHandleSelectUser);
  provide('sendHandleRemove', sendHandleRemove);

  const handleDelete = (id: number) => {
    groupData.value = groupData.value.filter((item) => {
      return item.userId != id;
    });
  };

  const handleCreate = () => {
    createShow.value = true;
  };
  const handleClose = () => {
    createShow.value = false;
  };
  const hanldFromData = async (value) => {
    submitData.value = value;
  };
  const getForm = throttle(async () => {
    myform.value.validate();
    await setTimeout(async () => {
      setLoading(true);
      if (myform.value.success) {
        try {
          const userIds = groupData.value.map((item) => {
            return item.userId;
          });
          const data = {
            ...submitData.value,
            userIds: userIds.toString(),
          };
          const { code } = await getGroupSave(qs.stringify(data));
          if (code == 0) {
            createShow.value = false;
            myform.value.reset();
          }
        } catch (error) {
          setLoadingFalse();
        } finally {
          setLoadingFalse();
        }
      }
      setLoadingFalse();
    });
  });

  const setLoadingFalse = () => {
    setTimeout(() => {
      setLoading(false);
    }, 500);
  };
  const reset = async () => {
    // let data = {};
    // myform.value.reset(data);
    await setTimeout(() => {
      myform.value.reset();
    });
  };
</script>

<style lang="scss" scoped>
  .page_content {
    &_tabs {
      height: 100vh;
      position: relative;
      :deep(.el-tabs__nav-scroll) {
        box-sizing: border-box;
        padding-left: 60px;
      }
    }
    &_group {
      height: calc(100vh - 51px);
      width: 300px;
      padding: 20px;
      box-sizing: border-box;
      border-top: 4px solid var(--el-menu-border-color);
      border-left: 1px solid var(--el-menu-border-color);
      height: 100%;
      overflow: hidden;
      .list {
        margin-top: 10px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        span {
          position: relative;
          cursor: default;
          background: var(--el-fill-color-blank);
          color: var(--el-tree-text-color);
          font-size: var(--el-font-size-base);
        }
        svg {
          cursor: pointer;
        }
      }
    }
    &_unit {
      box-sizing: border-box;
      padding-top: 10px;
      .left {
        display: flex;
        flex-direction: row;
        height: calc(100vh - 51px);
      }
      &_tree {
        padding: 20px;
        box-sizing: border-box;
        border-top: 4px solid var(--el-menu-border-color);
        border-right: 1px solid var(--el-menu-border-color);
        height: 100%;
        position: relative;
        overflow: hidden;
      }
      &_tables {
        height: $height;
        width: $width;
        :deep(th) {
          color: #000;
          background-color: rgba(9, 96, 189, 0.05);
          background-image: linear-gradient(rgba(9, 96, 189, 0.1), #fff);
        }
        :deep(.el-radio) {
          margin-right: 15px;
        }
        :deep(.el-radio:last-child) {
          margin-right: 0;
        }
        :deep(.el-radio--large) {
          height: 25px;
        }
      }
      .table_content_search {
        width: $width;
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-bottom: 20px;
        .button {
          margin-left: 20px;
        }
      }
    }

    :deep(.el-tabs__header) {
      margin: 0;
    }
  }
</style>
